package com.example.utils;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/*
 * 生成随机验证码
 */
@Controller
@RequestMapping("/")
public class CheckCode {


    //产生随机的字体
    private Font getFont(){
        //创建random对象,用于生产随机数
        Random random = new Random();
        //创建字体数组,用于封装不同字体的Font对象
        Font font[] = new Font[5];
        font[0] = new Font("Ravie", Font.PLAIN, 24);
        font[1] = new Font("Antique Olive Compact", Font.PLAIN, 24);
        font[2] = new Font("Forte", Font.PLAIN, 24);
        font[3] = new Font("Wide Latin", Font.PLAIN, 24);
        font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 24);

        return font[random.nextInt(5)];
    }

    @RequestMapping("/code")
    public String code(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //设置响应头类型
        response.setContentType("image/jpeg");
        OutputStream os = response.getOutputStream();
        int width = 83,  height = 30;
        //建立指定宽高和BufferedImage 对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();   //该画笔绘制于image上
        Color c = g.getColor();   //保存当前画笔颜色
        //填充矩形
        g.fillRect(0, 0, width, height);
        char [] ch = "abcdefghjkmnpqrstuvwxyz2345678901".toCharArray();
        //随机产生的字符串,不包括字母i、o、(小写), 数字0,1
        int length = ch.length;       //随机字符串的长度
        String sRand = "";            // 保存随机产生的字符串
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            //设置字体
            g.setFont(getFont());
            //随机生成0-9的数字
            String rand = new Character(ch[random.nextInt(length)]).toString();
            sRand += rand;
            //设置随机颜色
            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            g.drawString(rand, 20*i+6, 25);
        }
        //产生随机干扰点
        for (int i = 0; i < 20; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            g.drawOval(x1, y1, 2, 2);
        }
        //重设画笔的颜色
        g.setColor(c);
        //释放此图形的上下文及其使用的所有系统资源
        g.dispose();
        //将验证码记录到session中
        request.getSession().setAttribute("safeCode", sRand);
        //输出图像到页面中
        ImageIO.write(image, "JPEG", os);
        return null;
        /*
         * 此处只能return null ，
         * 写成 return "Manager/login" 会导致多次响应，
         * java.lang.IllegalStateException: getOutputStream() has already been called response
         */
    }
}
